package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    // 路径匹配器，支持通配符
     private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //1.获取本次请求的URI URI:统一资源标识符 URL:统一资源定位符
        String requestURI = req.getRequestURI();
        log.info("拦截到请求：{}", requestURI);

        String[] urls = new String[] {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/page/login.html",
                "/common/**",
                "/user/sendMsg",//移动端发送短信
                "/user/login",  //移动端登录
        };

        //2.判断是否需要登录
        boolean check = check(urls, requestURI);

        //3.如果不需要登录，直接放行
        if (check) {
            log.info("本次请求{}不需要登录，直接放行", requestURI);
            filterChain.doFilter(req, resp);
            return;
        }

        //4-1.判断登陆状态，如果已经登录，直接放行
        if (req.getSession().getAttribute("employee") != null) {
            Long empId = (Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            log.info("用户已登录，用户id为：{}", empId);
            filterChain.doFilter(req, resp);
            return;
        }

        //4-2.判断登陆状态，如果已经登录，直接放行
        if (req.getSession().getAttribute("user") != null) {
            Long userId = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            log.info("用户已登录，用户id为：{}", userId);
            filterChain.doFilter(req, resp);
            return;
        }

        log.info("用户未登录");
        //5.如果没有登录，跳转到登录页面
        resp.getWriter().write(JSON.toJSONString(R.error("NOT_LOGIN")));
        return;
    }

    /**  0
     * 检查请求路径是否需要登录
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            if (ANT_PATH_MATCHER.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
